package com.travel.server.manager.impl.command.message;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CommonUtil;
import com.travel.common.util.DateUtil;
import com.travel.common.util.MailUtils;
import com.travel.server.manager.dto.request.message.SendMessageRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.*;
import com.travel.server.manager.impl.enums.MessageTemplateEnum;
import com.travel.server.manager.impl.sal.MessageSal;
import com.travel.server.manager.impl.sms.SmsSal;
import com.travel.server.manager.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/5 18:22
 * @Desc:
 */
@Component
@Slf4j
public class SendMessageCommand extends AbstractCommand<SendMessageRequest, EmptyResponse> {

    @Autowired
    private MessageDal messageDal;

    @Autowired
    private OrderDal orderDal;

    @Autowired
    private CustomerDal customerDal;

    @Autowired
    private SpecialDal specialDal;

    @Autowired
    private ProjectDal projectDal;

    @Override
    protected void checkInput(SendMessageRequest request) {
        if(request.getTemplateId() == null || request.getType() == null){
            throwInvalidParam();
        }
        if(request.getId() == null && StringUtils.isBlank(request.getCustomerIdList())){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(SendMessageRequest request) {
        checkInput(request);

        MessageTemplate messageTemplate = messageDal.selectById(request.getTemplateId());
        String messageContent = messageTemplate.getMessageContent();

        if(request.getId() == null){
           if(messageContent.contains(MessageSal.PROJECT_NAME_TEMPLATE) || messageContent.contains(MessageSal.PROJECT_DATE_TEMPLATE)) {
               throwInvalidParam();
           }
        }

        List<CustomerInfo> list = new ArrayList<>();
        OrderInfo orderInfo;
        ProjectSpecial projectSpecial = null;
        ProjectInfo projectInfo = null;
        if(request.getId() != null) {
            orderInfo = orderDal.selectById(request.getId());
            projectSpecial = specialDal.selectById(orderInfo.getSpecialId());
            projectInfo = projectDal.selectById(projectSpecial.getProjectId());
            CustomerInfo customerInfo = customerDal.selectById(orderInfo.getCustomerId());
            list.add(customerInfo);
        }else if(request.getCustomerIdList() != null){
            List<Integer> customerIdList = CommonUtil.idsToList(request.getCustomerIdList());
            CustomerDal.CustomerParam param = new CustomerDal.CustomerParam();
            param.setIdList(customerIdList);
            list = customerDal.selectByExample(param);
        }

        if(MessageTemplateEnum.MSG.getType().equals(messageTemplate.getMessageType())){
            for(CustomerInfo customerInfo : list){
                if(customerInfo.getMobile() == null){
                    throw new WorkException(WorkCode.MSG_RECEIVE_NULL);
                }
            }
            for(CustomerInfo customerInfo : list){
                String content = messageContent;
                String param = makeSmsParam(content, projectInfo, projectSpecial, customerInfo);
                SmsSal.sendSms(messageTemplate.getSmsTemplateId(), param, customerInfo.getMobile());
            }

        }else if(MessageTemplateEnum.MAIL.getType().equals(messageTemplate.getMessageType())){
            for(CustomerInfo customerInfo : list){
                if(customerInfo.getMail() == null){
                    throw new WorkException(WorkCode.MAIL_RECEIVE_NULL);
                }
            }
            for(CustomerInfo customerInfo : list){
                String content = messageContent;
                content = makeContent(content, projectInfo, projectSpecial, customerInfo);
                sendMail(content, customerInfo.getMail(), messageTemplate.getMailTheme(), messageTemplate.getMailSender());
            }
        }


        return new EmptyResponse();
    }

    /**
     * 保持一下顺序不变，否则有问题
     * @param content
     * @return
     */
    private String makeContent(String content, ProjectInfo projectInfo, ProjectSpecial projectSpecial, CustomerInfo customerInfo){
        if(content.contains(MessageSal.PROJECT_NAME_TEMPLATE)){
            content = content.replace(MessageSal.PROJECT_NAME_TEMPLATE, projectInfo.getName());
        }
        if(content.contains(MessageSal.PROJECT_DATE_TEMPLATE)){
            if(projectSpecial.getTravelDate() != null) {
                content = content.replace(MessageSal.PROJECT_DATE_TEMPLATE, DateUtil.dateToStr(projectSpecial.getTravelDate(), DateUtil.YYYY_MM_DD));
            }
        }
        if(content.contains(MessageSal.NAME_TEMPLATE)){
            content = content.replace(MessageSal.NAME_TEMPLATE, customerInfo.getName());
        }
        if(content.contains(MessageSal.SEX_TEMPLATE)){
            String call = getCall(customerInfo.getSex());
            content = content.replace(MessageSal.SEX_TEMPLATE, call);
        }
        return content;
    }

    /**
     * 保持一下顺序不变，否则有问题
     * @param content
     * @return
     */
    private String makeSmsParam(String content, ProjectInfo projectInfo, ProjectSpecial projectSpecial, CustomerInfo customerInfo) {
        String param = CommonConstant.EMPTY_STR;
        if (content.contains(MessageSal.PROJECT_NAME_TEMPLATE)) {
            param = param + projectInfo.getName() + CommonConstant.COMMON_STR;
        }
        if (content.contains(MessageSal.PROJECT_DATE_TEMPLATE)) {
            if (projectSpecial.getTravelDate() != null) {
                param = param + DateUtil.dateToStr(projectSpecial.getTravelDate(), DateUtil.YYYY_MM_DD) + CommonConstant.COMMON_STR;
            }
        }
        if(content.contains(MessageSal.NAME_TEMPLATE)){
            param = param + customerInfo.getName() + CommonConstant.COMMON_STR;
        }
        if(content.contains(MessageSal.SEX_TEMPLATE)){
            String call = getCall(customerInfo.getSex());
            param = param + call + CommonConstant.COMMON_STR;
        }
        if(!StringUtils.isBlank(param)){
            param = param.substring(0, param.length() - 1);
        }
        return param;
    }

    private String getCall(String sex){
        if(StringUtils.isBlank(sex) || sex.equals(CommonConstant.SEX_UN_KNOW)){
            return CommonConstant.EMPTY_STR;
        }
        if(sex.equals(CommonConstant.SEX_MAN)){
            return CommonConstant.CALL_MAN;
        }
        if(sex.equals(CommonConstant.SEX_WOMAN)){
            return CommonConstant.CALL_WOMAN;
        }
        return CommonConstant.EMPTY_STR;
    }

    private void sendMail(String mail, String content, String theme, String sender){
        try {
            MailUtils.sendEmail(mail, content, theme, sender);
        }catch (Exception e) {
            log.error("发送邮件异常：", e);
            throw new WorkException(WorkCode.SEND_MAIL_ERROR);
        }
    }
}
